import re
import json
import logging
from django.shortcuts import render,HttpResponse
from  rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from .geetest import GeetestLib
from . import models
from .serializers import UserModelSerializer
from rest_framework_jwt.settings import api_settings

logger = logging.getLogger('django')

pc_geetest_id = '8845ffc862dc0597b30f78831369a27b',
pc_geetest_key = '2dc2dde1477594e1aebc5534ba3c080f',
class CaptchaAPIView(APIView):
    #  验证视图类
    def get(self, request):
        """获取验证码"""
        user_id = 'test'
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        status = gt.pre_process(user_id)
        response_str = gt.get_response_str()
        return HttpResponse(response_str)


from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from .utils import get_user_by_account

class UserAPIView(CreateAPIView):
    """ 注册新用户接口 """
    queryset = models.User.objects.all()
    serializer_class = UserModelSerializer


class MobileAPIView(APIView):
    def get(self,request,mobile):
        user = get_user_by_account(mobile)
        if user is not None:
            return Response({'msg':'抱歉，手机号已经被注册过了'},status=status.HTTP_400_BAD_REQUEST)
        return Response({'msg':'ok'})

class MobileLoginAPIView(APIView):
    def get(self,request,mobile):
        user = get_user_by_account(mobile)
        if user is None:
            return Response({'msg':'抱歉，手机号不存在'},status=status.HTTP_400_BAD_REQUEST)
        return Response({'msg':'ok'})


class SMSLoginAPIView(APIView):

    def post(self, request):

        mobile = request.data.get('mobile')
        user = get_user_by_account(mobile)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return Response({'token':user.token,'msg':'ok'})



import random
from django_redis import get_redis_connection
from luffyapi.settings import contants
from luffyapi.libs.yuntongxun.sms import CCP
class MSMAPIView(APIView):

    def get(self,request,mobile):
        #  首先查看下该手机号在60秒内是否发送过短信了

        redis_conn = get_redis_connection('sms_code')
        print('redis_conn==>',redis_conn)
        check_ret = redis_conn.get('mobile_%s' % mobile)
        # 找不到默认返回None
        if check_ret is not None:
            return Response({'msg':'60秒内已经发送过短信了,请稍后尝试！'},status=status.HTTP_400_BAD_REQUEST)

        # 1. 生成验证码
        try:
            sms_code = "%06d" % random.randint(0,999999)
            pipe = redis_conn.pipeline() #  开启redis管道
            pipe.multi()  #  开启批量操作

            pipe.setex('sms_%s' % mobile, contants.SMS_EXPIRE_TIME, sms_code) # --setex(k, 60, v)

            #  短信发送的时间间隔
            pipe.setex('mobile_%s' % mobile, contants.SMS_INTERVAL_TIME, '-')
            pipe.execute()  # 批量执行

            #  调用 短信发送的SDK 来发送短信
            # 引入celery 触发任务执行
            from mycelery.sms.tasks import send_sms
            send_sms.delay(sms_code, mobile)
            #
            #
            # ccp = CCP()
            # ret = ccp.send_template_sms('18800140015',[sms_code,contants.SMS_EXPIRE_TIME//60], 1)
            # print('ret>>>>',ret)
            # if not ret :
            #     logger.error("%s 发送短信失败" % mobile)
            #     return Response({'msg':'短信发送失败'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            return Response({'msg':'发送短信成功！'}) # 状态码不写默认200ok
        except :
            return Response({'msg': '内部错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ForgetPasswordAPIView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        sms_code = request.data.get('sms_code')
        redis_conn = get_redis_connection('sms_code')
        print('redis_conn==>', redis_conn)
        check_ret = redis_conn.get('sms_%s' % mobile).decode("UTF-8")
        print(sms_code, check_ret)
        if sms_code != check_ret:
            return Response({'msg':'验证码错误'}, status=status.HTTP_400_BAD_REQUEST)
        user = get_user_by_account(mobile)
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return Response({'token': user.token,'username':user.username,'id':user.id, 'msg': 'ok'})


class ResetPasswordAPIView(APIView):
    def post(self,request):
        print(request.data)
        username = request.data.get('username')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        re_password = request.data.get('re_password')
        email = request.data.get('email')
        print(username,)
        if password == re_password:
            #  调用 邮件发送的SDK 来发送短信
            # 引入celery 触发任务执行
            from mycelery.email.tasks import send_email
            send_email.delay(password, email)

            user_obj = models.User.objects.filter(username=username).first()
            print(user_obj)
            user_obj.set_password(password)
            user_obj.save()

        return Response({'msg': '您的密码修改已经成功请在 %s 邮件中查看密码' % email})










